<?php
class b2c_ctl_admin_sales_applyShenhe extends desktop_controller
{
    // public $workground = 'ectools_ctl_admin_order';
    var $certcheck = false;

    public function __construct($app)
    {
        parent::__construct($app);
        header("cache-control: no-store, no-cache, must-revalidate");
        $this->arr_status = array(
            '0' => app::get('b2c')->_('未审核'),
            '1' => app::get('b2c')->_('已通过'),
            '2' => app::get('b2c')->_('已拒绝'),
        );
    }

    public function index()
    {
        $this->workground = 'ectools.wrokground.order';
        $this->finder('b2c_mdl_order_apply_sale',array(
            'title'=>app::get('b2c')->_('折扣单审核'),
            'actions'=>array(
                array(
                    'label' => app::get('ectools')->_('导出'),
                    'target' => '_blank',
                    'submit'=>'index.php?app=b2c&ctl=admin_sales_applyShenhe&act=export',
                ),
            ),
            'use_buildin_set_tag'=>false,
            'use_buildin_recycle'=>false,
            'use_buildin_filter'=>true,
            'use_view_tab'=>true,
	        'use_buildin_export'=>false,
        ));
    }

    public function _views(){
        $mdl_aftersales = $this->app->model('order_apply_sale');
        $sub_menu = array(
            1=>array('label'=>app::get('b2c')->_('审核中'),'optional'=>false,'filter'=>array('shenhe_status'=>0,'pay_status'=>0)),
            2=>array('label'=>app::get('b2c')->_('已通过'),'optional'=>false,'filter'=>array('shenhe_status'=>1)),
            3=>array('label'=>app::get('b2c')->_('已拒绝'),'optional'=>false,'filter'=>array('shenhe_status'=>2)),
            4=>array('label'=>app::get('b2c')->_('已作废'),'optional'=>false,'filter'=>array('shenhe_status'=>0,'pay_status'=>1)),
        );

        if(isset($_GET['optional_view'])) $sub_menu[$_GET['optional_view']]['optional'] = false;

        foreach($sub_menu as $k=>$v){
            if($v['optional']==false){
                $show_menu[$k] = $v;
                if(is_array($v['filter'])){
                    $v['filter'] = array_merge(array(),$v['filter']);
                }else{
                    $v['filter'] = array();
                }
                $show_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
                if($k==$_GET['view']){
                    $show_menu[$k]['newcount'] = true;
                    $show_menu[$k]['addon'] = $mdl_aftersales->count($v['filter']);
                }
                $show_menu[$k]['href'] = 'index.php?app=b2c&ctl=admin_sales_applyShenhe&act=index&view='.($k).(isset($_GET['optional_view'])?'&optional_view='.$_GET['optional_view'].'&view_from=dashboard':'');
            }elseif(($_GET['view_from']=='dashboard')&&$k==$_GET['view']){
                $show_menu[$k] = $v;
            }
        }
        return $show_menu;
    }

    /**
     * @desc
     * @author guomin
     * @date 2018/5/17  10:40
     */
    public function save()
    {
        $apply_sale_id = $_POST['apply_sale_id'];
        $status = $_POST['shenhe_status'];
        $mdl_apply_sale = $this->app->model('order_apply_sale');
        $arr_apply_sale = $mdl_apply_sale->dump($apply_sale_id);
        if($status=='1'){
            $order_id=$arr_apply_sale['order_id'];
	        $discount=$arr_apply_sale['discount'];
            $sdf = array(
                'apply_sale_id' => $apply_sale_id,
                'shenhe_status' => $status,
            );
            $res=$mdl_apply_sale->save($sdf);
            //更新成功之后再更新orders表中的discount
            if($res){
                 $mdl_order=$this->app->model('orders');
                 $orders= $mdl_order->getRow('*',array('order_id'=>$order_id));
                 $df=array(
                     'zhekoudiscount'=>$discount,
                     'total_amount'=>round($orders['total_amount']-$discount,2),
                     'final_amount'=>round($orders['final_amount']-$discount,2),
                     'score_g'=>round($orders['final_amount']-$discount,2)
                 );
                 $result=$mdl_order->update($df,array('order_id'=>$order_id));
            }
        }elseif ($status=='2'){
            $sdf = array(
                'apply_sale_id' => $apply_sale_id,
                'shenhe_status' => $status,
            );
            $res=$mdl_apply_sale->save($sdf);
        }elseif ($status=='0'){//取消审核
	        $order_id=$arr_apply_sale['order_id'];
	        $discount=$arr_apply_sale['discount'];
	        $sdf = array(
		        'apply_sale_id' => $apply_sale_id,
		        'shenhe_status' => $status,
	        );

	        $res=$mdl_apply_sale->save($sdf);
	        //更新成功后修改orders表
	        if ($res){
		        $mdl_order=$this->app->model('orders');
		        $orders= $mdl_order->getRow('*',array('order_id'=>$order_id));
		        $df=array(
			        'zhekoudiscount'=>0,
			        'total_amount'=>$orders['total_amount']+$discount,
			        'final_amount'=>$orders['final_amount']+$discount
		        );
		        $result=$mdl_order->update($df,array('order_id'=>$order_id));
		        $text="折扣单取消审核";
	        }
        }
        //日志记录
        $orderLog = $this->app->model("order_log");
        $user_id=$this->user->user_id;
        $login_name=$this->user->user_data['account']['login_name'];
        $log_text[] = array(
            'txt_key'=> $text!='' ? $text :'打折单审核成功！',
            'data'=>array(
                $df,$sdf
            ),
        );
        $log_text = serialize($log_text);
        $sdf_order_log = array(
            'rel_id' => $order_id,
            'op_id' => $user_id,
            'op_name' => $login_name,
            'alttime' => time(),
            'bill_type' => 'order',
            'behavior' => 'updates',
            'result' => 'SUCCESS',
            'log_text' => $log_text,
        );
        $orderLog->save($sdf_order_log);
    }

    public function export(){
        $dbName='jxc_oubao';
        // $dbName='oubao_jxc';
        $sql = "SELECT
                 a.*,b.total_amount,c.compName,d.employName
            FROM  sdb_b2c_order_apply_sale AS a
            LEFT JOIN  sdb_b2c_orders AS b ON a.order_id = b.order_id
            LEFT JOIN  {$dbName}.jichu_client AS c ON b.member_id  = c.member_id
            LEFT JOIN  {$dbName}.jichu_employ AS d ON c.traderId  = d.id";
        if ($_POST['isSelectedAll'] == '_ALL_') {
            // $init_filter = array(
            //     '1'=>array('shenhe_status'=>0,'pay_status'=>0),
            //     '2'=>array('shenhe_status'=>1),
            //     '3'=>array('shenhe_status'=>2),
            //     '4'=>array('shenhe_status'=>0,'pay_status'=>1),
            // );
            $init_filter = array(
                '1'=>" WHERE a.shenhe_status='0' AND a.pay_status='0' ",
                '2'=>" WHERE a.shenhe_status='1' ",
                '3'=>" WHERE a.shenhe_status='2' ",
                '4'=>" WHERE a.shenhe_status='0' AND a.pay_status='1' ",
            );
            $dbName='jxc_oubao';
            // $dbName='oubao_jxc';
            $sql .= " {$init_filter[$_POST['view']]} ";
        }else{
            $filter = implode(',', $_POST['apply_sale_id']);
            $sql .= " WHERE a.apply_sale_id in({$filter}) ";
        }
        $data = kernel::database()->select($sql);
        $arr[] = array(
            '订单号',
            '客户名称',
            '业务员',
            '原价',
            '折扣价',
            '折扣率',
            '支付状态',
            '申请时间',
            '申请说明',
            '申请金额',
            '审核状态'
        );
        foreach ($data as $key => $value) {
            if ($value['shenhe_status'] ==0) { //未审核
                $totalMoney=$value['total_amount'];
                $zhekouMoney=$value['total_amount']-$value['discount'];
                $status = '未审核';
            }elseif ($value['shenhe_status'] ==1) {//已通过
                $totalMoney=$value['total_amount']+$value['discount'];
                $zhekouMoney=$value['total_amount'];
                $status = '已通过';
            }elseif ($value['shenhe_status'] ==2) {//已拒绝
                $totalMoney=$value['total_amount'];
                $zhekouMoney=$value['total_amount']-$value['discount'];
                $status = '已拒绝';
            }
            if ($value['pay_status'] == 0) {
                $pay_status = '未支付';
            }elseif ($value['pay_status'] == 1) {
                $pay_status = '已支付';
            }
            $arr[] = array(
                $value['order_id'],
                $value['compName'],
                $value['employName'],
                $totalMoney,
                $zhekouMoney,
                (round($zhekouMoney/$totalMoney,2)*100).'%',
                $pay_status,
                date('Y-m-d H:i:s',$value['add_time']),
                $value['zhekouinfo'],
                $value['discount'],
                $status
            );
        }
        $filetypeObj = kernel::single('importexport_type_xls');
        $filetypeObj->set_queue_header('折扣单审核.xls');
        $rs = $filetypeObj->fileHeader();
        foreach ($arr as $ref) {
            $rs .= $filetypeObj->arrToExportType(array($ref));
        }
        $rs .= $filetypeObj->fileFoot();
        echo $rs;
    }
}